#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll

#define MAX_THREADS 10

typedef struct MyData
{
    int val1;
    int val2;
    //char key[32];
}MYDATA;

DWORD WINAPI ThreadProc(LPVOID lpParam)
{
    MYDATA *pmd = (MYDATA *)lpParam;
    printf("%d\n", pmd->val1);
    printf("%d\n", pmd->val2);
    return 0;
}

DWORD(WINAPI *pThreadProc)(LPVOID lpParam);

void fun()
{
	pThreadProc = ThreadProc;
	MYDATA mydt[MAX_THREADS];

	HANDLE hThread[MAX_THREADS];
	int i;
	for ( i = 0; i < MAX_THREADS; i++ ) {
		mydt[i].val1 = i;
		mydt[i].val2 = i + 1;
		hThread[i] = CreateThread (
		                 NULL,// default security attributes
		                 0,// use default stack size
		                 pThreadProc,// thread function
		                 &mydt[i],// argument to thread function
		                 0, // use default creation flags
		                 NULL );
		if ( hThread[i] == NULL ) {
			ExitProcess ( i );
		}
	}
	// Wait until all threads have terminated.
	WaitForMultipleObjects ( MAX_THREADS, hThread, TRUE, INFINITE ); //这样传给回调函数的参数不用定位static或者new出来的了
	// Close all thread handles upon completion.
	for ( i = 0; i < MAX_THREADS; i++ ) {
		CloseHandle ( hThread[i] );
	}
}

bool initSock(){
}

DWORD WINAPI clientThread( LPVOID lpParam ){
	
	SOCKET clntSock = clntSocks[];
}

void handleClient( SOCKET clntSock ){
	char *str = "Hello World!";
	send ( clntSock, str, strlen ( str ) + sizeof ( char ), NULL );
}

struct ClientSocket{
	SOCKET socket;
	bool used;
}

int findUnusedSock( ){
	return 0;
}

SOCKET servSock;
ClientSocket clntSocks[50];
int idx = 0;
int listenThread()
{
	//初始化 DLL
	WSADATA wsaData;
	WSAStartup ( MAKEWORD ( 2, 2 ), &wsaData );
	//创建套接字
	servSock = socket ( PF_INET, SOCK_STREAM, IPPROTO_TCP );
	//绑定套接字
	sockaddr_in sockAddr;
	memset ( &sockAddr, 0, sizeof ( sockAddr ) ); //每个字节都用0填充
	sockAddr.sin_family = PF_INET; //使用IPv4地址
	sockAddr.sin_addr.s_addr = inet_addr ( "127.0.0.1" ); //具体的IP地址
	sockAddr.sin_port = htons ( 1234 ); //端口
	bind ( servSock, ( SOCKADDR* ) &sockAddr, sizeof ( SOCKADDR ) );
	//进入监听状态
	listen ( servSock, 20 );	//
	//接收客户端请求
	SOCKADDR clntAddr;
	int nSize = sizeof ( SOCKADDR );
	while(1){
		SOCKET clntSock = accept ( servSock, ( SOCKADDR* ) &clntAddr, &nSize );
	}
	//向客户端发送数据。是不是可以先recv?
	/*
	char *str = "Hello World!";
	send ( clntSock, str, strlen ( str ) + sizeof ( char ), NULL );
	*/
	return 0;
}

int closeListen(){
	//关闭套接字
	//closesocket ( clntSock );
	closesocket ( servSock );
	//终止 DLL 的使用
	WSACleanup();
	return 0;
}


